package com.srwl.mytx.activity;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.GoodsAdapterForLive;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.LiveRecord;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Present;
import com.srwl.mytx.domain.Reward;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.fragment.ConversationListFragment;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.AvatarListView;
import com.srwl.mytx.widget.BarrageLayout;
import com.srwl.mytx.widget.LiveCountDownView;
import com.srwl.mytx.widget.LiveMemberJoinSpecialView;
import com.srwl.mytx.widget.LiveMemberJoinView;
import com.srwl.mytx.widget.LiveOfferView;
import com.srwl.mytx.widget.LivePresentView;
import com.srwl.mytx.widget.RoomMessagesView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.srwl.mytx.adapter.OrderRecordAdapter.REQUEST_CODE_OFFER;


//import io.agora.rtc.Constants;
//import io.agora.rtc.IRtcEngineEventHandler;
//import io.agora.rtc.RtcEngine;
//import io.agora.rtc.video.VideoCanvas;

/**
 * Created by wei on 2016/6/12.
 */
public abstract class LiveBaseActivity extends BaseActivity implements LivePresentView.PresentListListener {
    protected static final String TAG = "LiveActivity";
    protected static final int COUNTDOWN_DELAY = 1000;
    protected static final int COUNTDOWN_START_INDEX = 5;//开始直播倒计时读秒
    public static final int COUNTDOWN_END_INDEX = 1;

    @BindView(R.id.left_gift_view1)
    LivePresentView leftGiftView;
    @BindView(R.id.left_gift_view2)
    LivePresentView leftGiftView2;
    @BindView(R.id.message_view)
    RoomMessagesView messageView;
    @BindView(R.id.bottom_bar)
    View bottomBar;
    @BindView(R.id.barrage_layout)
    BarrageLayout barrageLayout;
    @BindView(R.id.rv_audience_avatar)
    AvatarListView rv_audienceList;
    @BindView(R.id.audience_num)
    TextView tv_audienceNum;
    @BindView(R.id.new_messages_warn)
    ImageView newMsgNotifyImage;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.rl_goods_list)
    RecyclerView goodsRecyclerView;
    @BindView(R.id.live_member_join_view)
    LiveMemberJoinView liveMemberJoinView;
    @BindView(R.id.live_member_join_view_special)
    LiveMemberJoinSpecialView liveMemberJoinSpecialView;
    @BindView(R.id.offer_view)
    LiveOfferView offerView;
    @BindView(R.id.tv_offer_amount)
    TextView tv_offerAmount;
    @BindView(R.id.iv_offer)
    ImageView iv_offer;
    @BindView(R.id.fl_video_container)
    FrameLayout fl_VideoContainer;
    @BindView(R.id.iv_boo)
    ImageView iv_boo;
    @BindView(R.id.root_layout)
    RelativeLayout rootLayout;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.count_down_view)
    LiveCountDownView countDownView;
    @BindView(R.id.tv_current_price)
    TextView tv_advertisementPrice;
    @BindView(R.id.progress_bar_advertisement)
    ProgressBar progressBarAdvertisement;
    @BindView(R.id.rl_advertisement)
    RelativeLayout rl_advertisement;
    @BindView(R.id.cover_image)
    ImageView coverView;
    @BindView(R.id.iv_red_packet)
    ImageView iv_redPacket;
    @BindView(R.id.red_packet_num)
    TextView tv_red_Packet_Num;
    protected User anchor;
    protected Coupon childCoupon;
    protected boolean isMessageListInited;
    List<Reward> rewardList = Collections.synchronizedList(new LinkedList<Reward>());
    List<Orders> ordersList = new ArrayList<>();
    protected LinearLayoutManager layoutManager;
    //直播间所有观众账户列表
    protected List<String> accountList = new ArrayList<>();
    //直播间部分观众完整信息，因为用不着全部加载到本地，当用户去拖动观看的时候，再加载更多数据
    protected List<User> audienceList = new ArrayList<>();
    public GoodsAdapterForLive goodsAdapter;
    public List<Topic> goodsList = new ArrayList<>();
    LiveRoom liveRoom;
    protected static final int LIVE_ROOM_STATUS_STARTED = 1;//开始直播/直播中 非拍卖模式
    protected static final int LIVE_ROOM_STATUS_STOPED = 0;//直播停止
    protected static final int LIVE_ROOM_STATUS_AUCTION = 2;// 开始直播/直播中 拍卖模式
    //protected Coupon coupon ;
    protected List<Coupon> couponList = new ArrayList<>();
    //标记角色：是否是主播
    Boolean isAnchor;
    //标记是否是直播状态
    boolean isLiveStarted;
    //标记直播开始后是否更新侧滑中的主播发布的商品列表
    boolean isRefreshGoodsList;
    //ChatFragment fragment;
    DisplayMetrics dm;
    protected Topic bindGoods;
    private LinearLayoutManager linearLayoutManager;
    protected Gson gson;
    protected GsonBuilder builder;
    protected User myUserInfo;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver receiver;
    //protected RtcEngine mRtcEngine;
    // private IRtcEngineEventHandler mRtcEventHandler;
    private int booCount;//记录收到的点踩数量
    private List<ImageView> booViewList = new ArrayList<>();
    private boolean isOfferShowing;
    protected LiveRecord liveRecord;
    protected Advertisement advertisement;
    List<Present> presents;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        liveRoom = getIntent().getParcelableExtra("liveRoom");
        //直播
        initEventHandle();
        initializeAgoraEngine();
        onActivityCreate(savedInstanceState);
        leftGiftView.setListener(this);
        leftGiftView2.setListener(this);
        myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        builder = new GsonBuilder();
        gson = builder.create();
        // int status = MyApplication.getInstance().getmAgoraAPI().getStatus();
        //  Log.d(TAG, "登录状态" + status);

        initMessageView();
        rv_audienceList.init(liveRoom);
        initDrawerLayout();
        //加入频道
//        if (status != 2) {
//            Helper.getInstance().loginToAgora();
//        } else {
//            MyApplication.getInstance().getmAgoraAPI().channelJoin(liveRoom.getId());
//        }
    }

    private void initDrawerLayout() {
        mDrawerLayout.setScrimColor(Color.TRANSPARENT);//设置遮罩为透明
        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {
            }

            @Override
            public void onDrawerOpened(@NonNull View view) {
                rl_advertisement.setClickable(false);
                loadAdvertisementInfo();
                if (isLiveStarted && !isRefreshGoodsList && anchor != null) {
                    isRefreshGoodsList = true;
                    //下载主播的商品信息
                    loadAnchorGoods();
                }
            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
            }

            @Override
            public void onDrawerStateChanged(int i) {
            }
        });
    }

    /**
     * 当有主播在直播的时候，下载主播发布的商品显示到侧边栏
     */
    private void loadAnchorGoods() {
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .queryAnchorGoods(anchor.getuId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        List<Topic> topics = JSONObject.parseArray(JSON.toJSONString(result.getData()), Topic.class);
                        goodsList.addAll(topics);
                        goodsAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void loadAdvertisementInfo() {
        //  下载广告信息


    }

    protected void initGoodsList() {
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        goodsRecyclerView.setLayoutManager(linearLayoutManager);
        // goodsRecyclerView.getBackground().setAlpha(175);
        goodsRecyclerView.setHasFixedSize(true);

        goodsAdapter = new GoodsAdapterForLive(goodsList, LiveBaseActivity.this, isAnchor);
        goodsAdapter.setOnItemClickListener(new GoodsAdapterForLive.OnItemClickListener() {
            @Override
            public void goodsPhotoClick(View v, int position) {
            }

            @Override
            public void bindGoods(final View v, int position) {
                //没开始直播 不能绑定商品
                final Button btn_bind = (Button) v.findViewById(R.id.btn_bind);
                if (!isLiveStarted) {
                    btn_bind.setEnabled(true);
                    Toast.makeText(LiveBaseActivity.this, "尚未开始直播 无法绑定商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                LiveRoom updateLiveRoom = new LiveRoom();
                updateLiveRoom.setId(liveRoom.getId());
                Topic goods = new Topic();
                goods.setId(goodsList.get(position).getId());
                updateLiveRoom.setGoods(goods);
                updateLiveRoom.setStatus(LIVE_ROOM_STATUS_AUCTION);
//                updateLiveRoom.update(new UpdateListener() {
//                    @Override
//                    public void done(BmobException e) {
//                        if (e == null) {
//
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Toast.makeText(LiveBaseActivity.this, "绑定商品完成", Toast.LENGTH_SHORT).show();
//                                    btn_bind.setTextForSendMobileCodeButton("已经绑定");
//                                }
//                            });
//
//                        } else {
//
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    btn_bind.setEnabled(true);
//                                }
//                            });
//
//                        }
//                    }
//                });
            }
        });

        goodsRecyclerView.setAdapter(goodsAdapter);
    }


    @OnClick(R.id.rl_advertisement)
    public void toAdvertisementActivity_1() {

        startActivityForResult(new Intent(getBaseContext(), AdvertisementActivity.class)
                .putExtra("advertisement", advertisement), REQUEST_CODE_OFFER);
    }

    public void refreshGoodsList(String anchorId) {
        String bql = "getImageInfo include anchor,* from Goods where anchor=?";
//        new BmobQuery<Goods>().doSQLQuery(bql, new SQLQueryListener<Goods>() {
//            @Override
//            public void done(BmobQueryResult<Goods> bmobQueryResult, BmobException e) {
//                if (e == null) {
//                    if (bmobQueryResult != null) {
//                        goodsList.addAll(bmobQueryResult.getResults());
//                        goodsDateChange();
//                    }
//                }
//            }
//        }, anchorId);
    }


    protected abstract void onActivityCreate(@Nullable Bundle savedInstanceState);


    protected synchronized void showLeftGiftVeiw(Reward reward) {

        if (!leftGiftView.isUseGift(reward) && !leftGiftView2.isUseGift(reward)) {
            rewardList.add(reward);
        }

    }

    /**
     * 从服务端加载礼物信息
     */
    void initData() {

        RetrofitManager.getInstance().createRequest(LiveService.class).getAllPresent().enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                CommonResult body = response.body();

                // Log.d("返回的礼物数据:"+ (body.getData()))
                if (!response.isSuccessful()) {
                    Log.e(TAG, "onResponse: " + response.message());
                    return;
                }

                JSONArray jsonArray = (JSONArray) body.getData();
                if (jsonArray == null) {
                    return;
                }
                presents = jsonArray.toJavaList(Present.class);
                //setVp(mListener,presents);
                leftGiftView.setPresents(presents);
                leftGiftView2.setPresents(presents);
                Log.d(TAG, "礼物列表" + jsonArray.toJSONString());


            }


            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                Log.e(TAG, "礼物请求失败onFailure: " + t.getMessage());
            }
        });


    }

    /**
     * 从本地加载礼物信息
     */
    void initLocalData() {

        presents = new ArrayList<>();
        presents.add(new Present("1fen", R.drawable.p_1fen, 0.01));
        presents.add(new Present("2fen", R.drawable.p_2fen, 0.02));
        presents.add(new Present("5fen", R.drawable.p_5fen, 0.05));
        presents.add(new Present("1jiao", R.drawable.p_1jiao, 0.1));
        presents.add(new Present("2jiao", R.drawable.p_2jiao, 0.2));
        presents.add(new Present("5jiao", R.drawable.p_5jiao, 0.5));
        presents.add(new Present("1yuan", R.drawable.p_1yuan, 1.0));
        presents.add(new Present("2yuan", R.drawable.p_2yuan, 2.0));
        presents.add(new Present("5yuan", R.drawable.p_5yuan, 5.0));
        presents.add(new Present("10yuan", R.drawable.p_10yuan, 10.0));
        presents.add(new Present("50yuan", R.drawable.p_50yuan, 50.0));
        presents.add(new Present("100yuan", R.drawable.p_100yuan, 100.0));
    }

    private synchronized Reward getReward() {
        if (rewardList.size() == 0) {
            return null;
        }
        return rewardList.remove(0);
    }

    protected void showBooView() {
        ImageView booView = null;
        int randomY = 0;
        int randomX;
        for (int i = 0; i < booViewList.size(); i++) {
            ImageView imageView = booViewList.get(i);
            if (imageView.getTranslationY() == 0) {
                Random random = new Random();
                int max = Utils.dpToPx(100, this);
                randomY = random.nextInt(max);
                randomX = random.nextInt(max);
                if (random.nextBoolean()) {
                    randomY = -randomY;
                }
                if (random.nextBoolean()) {
                    randomX = -randomX;
                }
                imageView.setTranslationY(randomY);
                imageView.setTranslationX(randomX);
                Log.d(TAG, "showBooView: booViewList.size()" + booViewList.size() + "    i:" + i);
                booView = imageView;

                break;
            } else {
                if (i == booViewList.size() - 1) {
                    if (booViewList.size() < 10) {//屏幕上最多显示10个点踩图标
                        booView = getImageView();
                    } else {
                        return;//如果5个全都显示在屏幕上，那就return
                    }

                }
            }
        }
        if (booView == null) {
            booView = getImageView();
        }

        final ImageView finalBooView = booView;
        finalBooView.setVisibility(View.VISIBLE);
        ViewAnimator.animate(booView)
                .alpha(0, 1).scale(3, 1).duration(400)
                .thenAnimate(booView)
                .translationY(0 + randomY, -70 + randomY, 30 + randomY, -70 + randomY, 30 + randomY, -70 + randomY, 30 + randomY).rotation(0, -30, 0, -30, 0, -30, 0).duration(1500)
                .thenAnimate(booView)
                .alpha(1, 0).translationY(1.5f * iv_boo.getHeight() + randomY).duration(600)
                .onStop(new AnimationListener.Stop() {
                    @Override
                    public void onStop() {
                        booCount--;
                        finalBooView.setTranslationY(0);
                        if (booCount >= 1) {
                            showBooView();
                        }
                    }
                })
                .start();
    }

    @NonNull
    private ImageView getImageView() {

        ImageView booView = new ImageView(this);
        booView.setBackgroundResource(R.drawable.tx_boo);
        RelativeLayout.LayoutParams params = getLayoutParams();
        booView.setVisibility(View.GONE);
        rootLayout.addView(booView, params);
        booViewList.add(booView);
        return booView;
    }

    @NonNull
    private RelativeLayout.LayoutParams getLayoutParams() {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//        Random random = new Random();
//        int i = random.nextInt(Utils.dpToPx(100, this));//生成随机数
//        params.bottomMargin = screenHeight / 2 - i;
//        int leftMargin = (int) ((screenWidth - iv_boo.getWidth()) * Math.random());
//        params.leftMargin = leftMargin < iv_boo.getWidth() ? iv_boo.getWidth() : leftMargin;
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        return params;
    }


    protected void goodsDateChange() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (goodsAdapter == null) {
                    return;
                }
                goodsAdapter.notifyDataSetChanged();
            }
        });
    }

    protected void showOffer(final Orders orders) {
        if (isOfferShowing) {
            ordersList.add(orders);
            return;
        }
        isOfferShowing = true;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                offerView.setupView(orders);
                if (!offerView.isShown()) {
                    offerView.setVisibility(View.VISIBLE);
                }
                if (!tv_offerAmount.isShown()) {
                    tv_offerAmount.setVisibility(View.VISIBLE);
                }
                tv_offerAmount.setText(Utils.numberFormat(orders.getAmount()));
                ViewAnimator.animate(tv_offerAmount)
                        .alpha(0, 1)
                        .scale(4, 1)
                        .duration(800)
                        .onStop(() -> {
                            isOfferShowing = false;
                            if (ordersList.size() != 0) {
                                showOffer(ordersList.remove(0));
                            }
                        })
                        .start()
                ;
            }
        });
    }

    protected void initMessageView() {

        messageView.init(liveRoom);
        messageView.setMessageViewListener(new RoomMessagesView.MessageViewListener() {
            @Override
            public void onMessageSend(Message content) {
//                Message message = new Message();
//                // message.setuId(myUserInfo.getuId());
//                message.setTitle(myUserInfo.getUsername());
//                message.setContent(content);
//                message.setType(0);
                // MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");


                //messageView.setData(message);
                Utils.hideKeyboard(messageView.getInputView());
            }

//            @Override
//            public void onItemClickListener(final Message message) {
            //if(message.getFrom().equals(EMClient.getInstance().getCurrentUser())){
            //    return;
            //}

            //  showUserDetailsDialog(clickUsername);
            // }

//            @Override
//            public void onHiderBottomBar() {
//                bottomBar.setVisibility(View.VISIBLE);
//            }
        });
        messageView.setVisibility(View.VISIBLE);
        messageView.setShowInputView(false);
        // bottomBar.setVisibility(View.VISIBLE);
        isMessageListInited = true;
        //  updateUnreadMsgView();


    }


    /* private void showUserDetailsDialog(User user) {
         final UserDetailsDialog dialog =
                 UserDetailsDialog.newInstance(user);
         dialog.setUserDetailsDialogListener(
                 new UserDetailsDialog.UserDetailsDialogListener() {
                     @Override
                     public void onMessageClick(User user) {
                         dialog.dismiss();
                         Bundle bd = new Bundle();
                         // bd.putCharSequence("userId", user.getuId());
                         bd.putParcelable(Constant.EXTRA_TARGET_USER_INFO, user);
                         ChatFragment chatFragment = new ChatFragment();
                         chatFragment.setArguments(bd);
                         chatFragment.show(getSupportFragmentManager(), "ChatFragment");
                     }

                     @Override
                     public void onMentionClick(String username) {
                         dialog.dismiss();
                         messageView.getInputView().setText("@" + username + " ");
                         showInputView();
                     }
                 });
         dialog.show(getSupportFragmentManager(), "UserDetailsDialog");
     }
 */
    private void showInputView() {
        bottomBar.setVisibility(View.INVISIBLE);
        messageView.setShowInputView(true);
        messageView.setVisibility(View.VISIBLE);
        messageView.getInputView().requestFocus();
        messageView.getInputView().requestFocusFromTouch();
        Utils.showKeyboard(messageView.getInputView());

//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Utils.showKeyboard(messageView.getInputView());
//
//            }
//        }, 200);
    }

    protected void refreshAudienceNumber() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_audienceNum.setText(String.valueOf(accountList.size()));

            }
        });
    }

    private void refreshAudienceList(List<User> userList) {

        audienceList.addAll(userList);


        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_audienceNum.setText(String.valueOf(audienceList.size()));
                // rv_audienceList.getAdapter().notifyDataSetChanged();
            }
        });


    }

    /**
     * 顶部观众列表 封装到AvatarRecyclerView去了
     */
   /* private void initAudienceListView() {
        audienceList = new ArrayList<>();
        layoutManager = new LinearLayoutManager(LiveBaseActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_audienceList.setLayoutManager(layoutManager);
       // avatarAdapter = new AvatarAdapter(LiveBaseActivity.this, audienceList);
        rv_audienceList.setAdapter(avatarAdapter);
    }*/
    protected void onUserExited(String userId) {

//        for (int i = 0; i < accountList.size(); i++) {
//            if (accountList.get(i).equals(userId)) {
//                accountList.remove(i);
//                break;
//            }
//        }
        accountList.remove(userId);
        for (int i = 0; i < audienceList.size(); i++) {

            if (TextUtils.equals(audienceList.get(i).getuId(), userId)) {
                audienceList.remove(i);
                break;
            }

        }

//        if (anchor != null) {
//            if (anchor.getuId().equals(userId)) {
//                showToast(bottomBar, "直播结束");
//                liveStatusListener.onLiveStop();
//                isLiveStarted = false;
//                anchor = null;
//            }
//        }
        notifyLiveRoomMemberChange();

    }

    protected void notifyLiveRoomMemberChange() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                tv_audienceNum.setText(String.valueOf(accountList.size()));
                // rv_audienceList.getAdapter().notifyDataSetChanged();
            }
        });

    }

    @OnClick(R.id.root_layout)
    void onRootLayoutClick() {
        // periscopeLayout.addHeart();
    }

    @OnClick(R.id.rl_comment)
    void onCommentImageClick() {
        showInputView();
    }


    @OnClick(R.id.chat_image)
    void onChatImageClick() {
        ConversationListFragment fragment = new ConversationListFragment();
//    getSupportFragmentManager().beginTransaction()
//        .replace(R.id.message_container, fragment)
//        .commit();
        fragment.show(getSupportFragmentManager(), "ConversationListFragment");
    }

//    @OnClick(R.id.screenshot_image)
//    void onScreenshotImageClick() {
//    Bitmap bitmap = screenshot();
//    if (bitmap != null) {
//      ScreenshotDialog dialog = new ScreenshotDialog(this, bitmap);
//      dialog.show();
//    }
//
//    }

    private Bitmap screenshot() {
        // 获取屏幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        return bmp;
    }

    @Override
    public void onDisappear() {
        Reward reward = getReward();
        if (reward == null) {
            return;
        }

        showLeftGiftVeiw(reward);


        // TODO: 2019/3/24 遍历礼物集合 如果是同一用户同类型礼物则合并 并增加计数


        // List<Reward> rewardList1 = new ArrayList<>();
        for (int i = 0; i < rewardList.size(); i++) {
            Reward reward3 = rewardList.get(i);
            if (reward != null
                    && reward3.getuId().equals(reward.getuId())
                    && Double.doubleToLongBits(reward3.getAmount()) == Double.doubleToLongBits(reward.getAmount())) {

                reward3 = rewardList.remove(i);
                Log.d(TAG, "Reward3的id " + reward3.getuId());
                i--;
                //rewardList1.add(reward);


                showLeftGiftVeiw(reward3);
            }

        }

    }

    protected LiveStatusListener liveStatusListener;

    public void setOnLiveStatusChangeListener(LiveStatusListener liveStatusListener) {
        this.liveStatusListener = liveStatusListener;
    }


    void resetLiveRoom() {
        anchor = null;
        bindGoods = null;
        goodsList = null;
    }


    private void initializeAgoraEngine() {
//        try {
//            mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_id), mRtcEventHandler);
//        } catch (Exception e) {
//            Log.e(TAG, Log.getStackTraceString(e));
//
//            throw new RuntimeException("NEED TO check rtc sdk setupView fatal error\n" + Log.getStackTraceString(e));
//        }
//        //设置直播模式，模式是视频通话模式
//        mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
//        //开始视频
//        mRtcEngine.enableVideo();
//        //设置视频编码
//        mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, true);
//        //设置双流模式
//        mRtcEngine.enableDualStreamMode(true);
    }

    protected void joinChannel(String channelId) {
        //  mRtcEngine.joinChannel("", channelId, "Extra Optional Data", 0);
    }

    /**
     * 设置角色：主播或者是观众
     *
     * @param
     */
    protected void setClientRole(int role) {

        //mRtcEngine.setClientRole(role);

    }

    /**
     * 关掉或者打开本地的视频和语音，直播间的观众需要关闭，
     *
     * @param mute true 关掉 false 打开
     */
    protected void muteLocalVideoStream(boolean mute) {
        // mRtcEngine.muteLocalVideoStream(mute);
        //  mRtcEngine.muteLocalAudioStream(mute);
    }

    protected void setLocalVideo() {

//        SurfaceView surfaceViewLocal = RtcEngine.CreateRendererView(getBaseContext());
//        surfaceViewLocal.setZOrderOnTop(true);
//        surfaceViewLocal.setZOrderMediaOverlay(true);
//        surfaceViewLocal.setTag("local");
//        rl_videoContainer.addView(surfaceViewLocal, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//
//        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceViewLocal, VideoCanvas.RENDER_MODE_HIDDEN, 0));
//
//        //设置预览
//        mRtcEngine.startPreview();
    }

    protected void setRemoteVideo(int uid) {

//        SurfaceView surfaceViewRemote = RtcEngine.CreateRendererView(getBaseContext());
//        surfaceViewRemote.setZOrderOnTop(true);
//        surfaceViewRemote.setZOrderMediaOverlay(true);
//        surfaceViewRemote.setTag("remote");
//
//        rl_videoContainer.addView(surfaceViewRemote, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceViewRemote, VideoCanvas.RENDER_MODE_HIDDEN, uid));
        // mRtcEngine.setRemoteDefaultVideoStreamType(VIDEO_STREAM_HIGH);
    }

    /**
     * 清空视频容器
     */
    protected void removeVideoView() {
        fl_VideoContainer.removeAllViews();
    }

    private void initEventHandle() {
//        mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1
//            @Override
//            public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
//                Log.d(TAG, "进入直播频道成功：" + channel + ":" + uid);
//                if (bottomBar.getVisibility() == View.GONE) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            bottomBar.setVisibility(View.VISIBLE);
//
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void onUserJoined(final int uid, int elapsed) {
//
//                Log.d(TAG, "直播频道：有主播开播：" + uid);
//                if (liveStatusListener != null) {
//                    liveStatusListener.onAnchorJoin();
//                }
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        setRemoteVideo(uid);
//                    }
//                });
//
//
//            }
//
//            @Override
//            public void onError(int err) {
//                Log.e(TAG, "直播频道错误：" + err);
//            }
//
//            @Override
//            public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) { // Tutorial Step 5
//                Log.d(TAG, "直播频道：第一次视频解码" + uid);
//                isLiveStarted = true;
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        if (liveStatusListener != null) {
////                            liveStatusListener.startLive();
////                            isLiveStarted=true;
////                        }
//
//                        //   setRemoteVideo(uid);
//
//
//                    }
//                });
//            }
//
//            @Override
//            public void onUserOffline(int uid, int reason) { // Tutorial Step 7
//                Log.d(TAG, "直播频道：有主播离线" + uid);
//                if (liveStatusListener != null) {
//                    liveStatusListener.onAnchorLeave();
//                }
//
//            }
//
//            @Override
//            public void onAudioRouteChanged(int routing) {
//                Log.d(TAG, "直播频道：远程音频变化");
//            }
//
//            @Override
//            public void onUserMuteVideo(final int uid, final boolean muted) { // Tutorial Step 10
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (muted) {
//                            if (liveStatusListener != null && isLiveStarted) {
//                                Log.d(TAG, "直播频道：远程视频隐藏");
//                                //  liveStatusListener.onLiveStop();
//                                isLiveStarted = false;
//                            }
//                        } else {
//                            Log.d(TAG, "直播频道：远程视频显示");
//                            if (liveStatusListener != null) {
//                                liveStatusListener.startLive();
//
//                            }
//                        }
//                        //onRemoteUserVideoMuted(uid, muted);
//                    }
//                });
//            }
//        };
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        broadcastManager.unregisterReceiver(receiver);
//        MyApplication.getInstance().getmAgoraAPI().channelLeave(liveRoom.getId());
//        //mRtcEngine.leaveChannel();
//
//        mRtcEventHandler = null;

    }

    protected void showAdvertisement(Advertisement advertisement) {
        if (advertisement != null) {
            if (advertisement.getVideo() != null) {
                //Glide.with(LiveBaseActivity.this).load(advertisement.getVideo()).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
                GlideLoadUtils.glideLoad(this, advertisement.getVideo(), coverView);
                // TODO: 2019/1/25 判断是否在直播，如果没有直播就播放广告视频
            } else {
                //Glide.with(LiveBaseActivity.this).load(advertisement.getPicture()).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
                GlideLoadUtils.glideLoad(this, advertisement.getPicture(), coverView);

            }
        }
    }


    private void removeAdvertisement() {
        Glide.with(LiveBaseActivity.this).load(liveRoom.getCover()).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
    }

    public interface LiveStatusListener {
        void onAnchorJoin();

        void prepareStartLive();

        void startLive();

        void onAnchorLeave();

        void stopLive();


        /**
         * 直播限时结束
         */
        void timeOut();
    }

    /**
     * 晃动动画
     *
     * @param counts
     * @return
     */
    public static Animation shakeAnimation(int counts) {
        Animation rotateAnimation = new RotateAnimation(0, 20, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setInterpolator(new CycleInterpolator(counts));
        rotateAnimation.setRepeatCount(-1);
        rotateAnimation.setDuration(3000);
        return rotateAnimation;
    }
}
